package top.roadvast.springboot.utils;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author 郭泽鹏
 * @Date 2021/10/22 16:18
 * @Version 1.0
 * @Description 获取当前时间工具类：开启一个单个调度线程按毫秒更新时间戳
 */
public class CurrentTimeMillsUtil {
    private volatile long now;

    public CurrentTimeMillsUtil() {
        this.now = System.currentTimeMillis();;
        scheduleTick();
    }

    private void scheduleTick() {
        new ScheduledThreadPoolExecutor(1, runnable -> {
            Thread thread = new Thread(runnable, "current-time-millis");
            thread.setDaemon(true);
            return thread;
        }).scheduleAtFixedRate(() -> {
            //command：执行线程
            //initialDelay：初始化延时
            //period：两次开始执行最小间隔时间
            //unit：计时单位
            now = System.currentTimeMillis();
        }, 1, 1, TimeUnit.MILLISECONDS);
    }

    public long now() {
        return now;
    }

    public static CurrentTimeMillsUtil getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final CurrentTimeMillsUtil INSTANCE = new CurrentTimeMillsUtil();
    }
}
